#ifndef __SV2_SAVER__
#define __SV2_SAVER__

#include "sms_core.h"
#include <string>
#include <chrono>
#include <mutex>
#include <queue>
#include <condition_variable>
#include "sv2_video_saver.h"


namespace sv2
{

  class VideoWriter;

  class SaverCppNode : public sms::BaseNode
  {
  public:
    SaverCppNode(
        std::string job_name,
        std::string param_file,
        std::string specified_input_topic,
        std::string ip = "127.0.0.1",
        int port = 9094) : sms::BaseNode("SaverCppNode", job_name, param_file, ip, port),
                           _det_res_sub(specified_input_topic, "memory_msgs::RawImage", std::bind(&SaverCppNode::full_res_callback, this, std::placeholders::_1))
    {
      // 读取节点参数
      this->_image_width = this->get_param("image_width", 1280);
      this->_image_height = this->get_param("image_height", 720);
      this->_fps = this->get_param("fps", 25);
      this->_saver_dir = this->get_param("saver_dir", "/home/amov");
      
      logger.info("image_width: " + std::to_string(static_cast<int>(this->_image_width)));
      logger.info("image_height: " + std::to_string(static_cast<int>(this->_image_height)));
      logger.info("fps: " + std::to_string(static_cast<int>(this->_fps)));
      logger.info("saver_dir: " + this->_saver_dir);


      // 默认设置保存路径"/home/amov/Videos"，保存图像尺寸（640，480），帧频25Hz，同步保存检测结果（.svj）
      this->_vw.setup(this->_saver_dir, cv::Size(this->_image_width, this->_image_height), this->_fps, true);
   
   
    }
    ~SaverCppNode()
    {
    }
    void run();

    void full_res_callback(nlohmann::json msg)
    {
      // 放入到阻塞队列中
      {
        std::unique_lock<std::mutex> lock(this->_full_queue_mtx);
        this->_full_queue.push(msg);
      }
      // 通知主线程取数据
      this->_full_cv.notify_one();
    }

    int _image_width;
    int _image_height;
    int _fps;
    std::string _saver_dir;
    VideoWriter _vw;

  private:
    // 订阅话题
    sms::Subscriber _det_res_sub;

    std::mutex _full_queue_mtx;
    std::queue<nlohmann::json> _full_queue;
    std::condition_variable _full_cv;

};

}
#endif
